from flask import Flask, render_template, request, redirect, url_for, session, send_from_directory
import pandas as pd
from pyecharts import options as opts
from pyecharts.charts import Bar, Pie, Scatter, Boxplot, Tab
from pyecharts.components import Table
from pyecharts.globals import ThemeType
import os

app = Flask(__name__)
app.secret_key = 'your_secret_key_here'  # 用于会话加密

# 简单的用户数据库
USERS = {
    'admin': 'admin123',
    'user': 'user123'
}


@app.route('/', methods=['GET', 'POST'])
def login():
    if request.method == 'POST':
        username = request.form.get('username')
        password = request.form.get('password')

        if not username or not password:
            return render_template('login.html', error="用户名和密码不能为空")

        if username in USERS and USERS[username] == password:
            session['logged_in'] = True
            session['username'] = username
            return redirect(url_for('visualization'))
        else:
            return render_template('login.html', error="用户名或密码不正确")

    return render_template('login.html')


@app.route('/visualization')
def visualization():
    if not session.get('logged_in'):
        return redirect(url_for('login'))

    # 读取数据并生成可视化
    try:
        df_csv = pd.read_csv('D:/keshe2/Processors.csv', on_bad_lines='skip', sep=';')
    except Exception as e:
        return f"数据加载错误: {str(e)}", 500

    # 创建所有图表
    charts = {
        'data_overview': create_data_overview(df_csv),
        'year_distribution': create_year_distribution(df_csv),
        'designer_share': create_designer_share(df_csv),
        'core_data_rate': create_core_data_rate(df_csv),
        'clock_frequency': create_clock_frequency(df_csv),
        'data_stats': create_data_stats(df_csv)
    }

    return render_template('visualization.html',
                           username=session.get('username'),
                           charts=charts)


@app.route('/logout')
def logout():
    session.clear()
    return redirect(url_for('login'))


# 图表生成函数
def create_data_overview(df):
    table = Table()
    headers = ["字段名", "数据类型", "描述"]
    rows = [
        ["Year Released", "数值", "发布年份"],
        ["Designer", "字符串", "设计商"],
        ["Number of processor core(s)", "数值", "处理器核心数量"],
        ["Max. Data Rate", "字符串", "最大数据速率"],
        ["Semiconductor Technology", "字符串", "半导体技术"],
        ["Max. Clock Frequency of Memory IF", "字符串", "内存接口最大时钟频率"]
    ]
    table.add(headers, rows).set_global_opts(
        title_opts=opts.ComponentTitleOpts(title="数据字段概览", subtitle="处理器数据集基本信息")
    )
    return table.dump_options_with_quotes()


def create_year_distribution(df):
    year_counts = df['Year Released'].value_counts().sort_index().reset_index()
    year_counts.columns = ['Year Released', '数量']

    bar_year = (
        Bar(init_opts=opts.InitOpts(theme=ThemeType.LIGHT))
        .add_xaxis(year_counts['Year Released'].astype(str).tolist())
        .add_yaxis("数量", year_counts['数量'].tolist())
        .set_global_opts(
            title_opts=opts.TitleOpts(title="不同年份发布的处理器数量"),
            xaxis_opts=opts.AxisOpts(name="发布年份"),
            yaxis_opts=opts.AxisOpts(name="处理器数量"),
            toolbox_opts=opts.ToolboxOpts(is_show=True),
            datazoom_opts=[opts.DataZoomOpts()]
        )
    )
    return bar_year.dump_options_with_quotes()


def create_designer_share(df):
    designer_counts = df['Designer'].value_counts().reset_index()
    designer_counts.columns = ['Designer', '数量']

    pie_designer = (
        Pie(init_opts=opts.InitOpts(theme=ThemeType.LIGHT))
        .add(
            "设计商",
            [list(z) for z in zip(designer_counts['Designer'], designer_counts['数量'])],
            radius=["30%", "75%"],
            rosetype="radius",
        )
        .set_global_opts(
            title_opts=opts.TitleOpts(title="不同设计商的处理器数量占比"),
            legend_opts=opts.LegendOpts(orient="vertical", pos_top="15%", pos_left="2%"),
            toolbox_opts=opts.ToolboxOpts(is_show=True)
        )
        .set_series_opts(
            label_opts=opts.LabelOpts(formatter="{b}: {c} ({d}%)"),
            tooltip_opts=opts.TooltipOpts(formatter="{a} <br/>{b}: {c} ({d}%)")
        )
    )
    return pie_designer.dump_options_with_quotes()


def create_core_data_rate(df):
    df['Max. Data Rate Numeric'] = df['Max. Data Rate'].str.extract(r'(\d+\.?\d*)').astype(float)
    valid_data = df.dropna(subset=['Number of processor core(s)', 'Max. Data Rate Numeric'])

    scatter = (
        Scatter(init_opts=opts.InitOpts(theme=ThemeType.LIGHT))
        .add_xaxis(valid_data['Number of processor core(s)'].tolist())
        .add_yaxis(
            "最大数据速率",
            valid_data['Max. Data Rate Numeric'].tolist(),
            symbol_size=10,
            label_opts=opts.LabelOpts(is_show=False),
        )
        .set_global_opts(
            title_opts=opts.TitleOpts(title="处理器核心数量与最大数据速率的关系"),
            xaxis_opts=opts.AxisOpts(name="处理器核心数量"),
            yaxis_opts=opts.AxisOpts(name="最大数据速率 (Gbyte/s)"),
            toolbox_opts=opts.ToolboxOpts(is_show=True),
            visualmap_opts=opts.VisualMapOpts(
                dimension=1,
                pos_left="right",
                min_=valid_data['Max. Data Rate Numeric'].min(),
                max_=valid_data['Max. Data Rate Numeric'].max(),
                range_text=["高", "低"],
                is_calculable=True
            )
        )
        .set_series_opts(
            tooltip_opts=opts.TooltipOpts(formatter="{a}: {b}核心, {c}Gbyte/s")
        )
    )
    return scatter.dump_options_with_quotes()


def create_clock_frequency(df):
    df['Max. Clock Frequency'] = df['Max. Clock Frequency of Memory IF'].str.extract(r'(\d+\.?\d*)').astype(float)

    boxplot_data = []
    valid_technologies = []

    tech_groups = df.groupby('Semiconductor Technology')['Max. Clock Frequency']
    for tech, group in tech_groups:
        valid_data = group.dropna().tolist()
        if len(valid_data) >= 4:
            boxplot_data.append(valid_data)
            valid_technologies.append(tech)

    boxplot = (
        Boxplot(init_opts=opts.InitOpts(theme=ThemeType.LIGHT))
        .add_xaxis(valid_technologies)
        .add_yaxis(
            "",
            Boxplot.prepare_data(boxplot_data),
            tooltip_opts=opts.TooltipOpts(formatter="{b}: {a}")
        )
        .set_global_opts(
            title_opts=opts.TitleOpts(title="不同半导体技术的最大时钟频率分布"),
            xaxis_opts=opts.AxisOpts(name="半导体技术", axislabel_opts={"rotate": 45}),
            yaxis_opts=opts.AxisOpts(name="最大时钟频率 (MHz)"),
            toolbox_opts=opts.ToolboxOpts(is_show=True)
        )
    )
    return boxplot.dump_options_with_quotes()


def create_data_stats(df):
    stats_table = Table()
    stats_headers = ["统计项", "值"]
    stats_rows = [
        ["总记录数", len(df)],
        ["设计商数量", df['Designer'].nunique()],
        ["年份跨度", f"{df['Year Released'].min()} - {df['Year Released'].max()}"],
        ["平均核心数", round(df['Number of processor core(s)'].mean(), 2)],
        ["半导体技术种类", df['Semiconductor Technology'].nunique()]
    ]
    stats_table.add(stats_headers, stats_rows).set_global_opts(
        title_opts=opts.ComponentTitleOpts(title="数据统计摘要")
    )
    return stats_table.dump_options_with_quotes()


if __name__ == '__main__':
    app.run(debug=True)